import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/socket/dto/business/WebRtcData.dart';
import 'package:im_app/im/util/HexColor.dart';
import 'package:im_app/im/util/ImCacheFactory.dart';
import 'package:im_app/im/util/ImSingleton.dart';

import '../page/bloc/WebRtcCubit.dart';
import '../page/sub/WebRtcAudioPage.dart';
import '../page/sub/WebRtcVideoPage.dart';
import '../pojo/ImPojo.dart';
import '../socket/service/RpcSendDataService.dart';
import '../util/LoggerUtil.dart';

class WebRtcInvitationDialog extends StatelessWidget {
  final _logger = createLogger();

  final WebRtcInvitationReq webRtcInvitationReq;
  OverlayEntry? overlayEntry;

  WebRtcInvitationDialog({required this.webRtcInvitationReq, super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: HexColor.fromHex("#D5D4D4FF"),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.only(left: 20, right: 20),
          child: Container(
            height: 200,
            decoration: const BoxDecoration(
                color: Colors.white60,
                border: Border.fromBorderSide(BorderSide(color: Colors.grey)),
                borderRadius: BorderRadius.all(Radius.circular(20.0))),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Padding(
                    padding: EdgeInsets.only(top: 10, left: 10),
                    child: Text('视频邀请', style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16))),
                Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Text.rich(TextSpan(
                      children: [
                        TextSpan(
                            text: webRtcInvitationReq.fromUserId,
                            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
                        const TextSpan(text: '邀请您进行语音通信', style: TextStyle(fontSize: 20)),
                      ],
                    ))),

                const Expanded(child: Text('')),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      TextButton(child: const Text('接受'), onPressed: () => _accept(context)),
                      TextButton(child: const Text('拒绝'), onPressed: () => _reject(context)),
                      const SizedBox(width: 20,),
                    ],
                  ),
                ),
                const SizedBox(height: 10,),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _accept(BuildContext context) async {
    var rpcWebRtcService = RpcWebRtcService();
    rpcWebRtcService.sendWebRtcInvitationResult(WebRtcInvitationResultReq(toUserId: webRtcInvitationReq.fromUserId!, isAccept: true))
        .then((okResp) => _logger.i('[WebRtcClient accept invitation], success'));

    overlayEntry?.remove();

    var loginUserId = ImSingleton.getInstance().session.userId;
    var userSet = <ImUser>{};
    for (var userId in webRtcInvitationReq.userIds) {
      if (userId == loginUserId) continue;
      var user = await ImCacheFactory.getInstance().getImUser(userId);
      userSet.add(user!);
    }
    var fromUser = await ImCacheFactory.getInstance().getImUser(webRtcInvitationReq.fromUserId!);
    userSet.add(fromUser!);

    Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
      var webRtcCubit = context.read<WebRtcCubit>();
      var screenWidth = MediaQuery.of(context).size.width;
      var screenHeight = MediaQuery.of(context).size.height;
      if (webRtcInvitationReq.chatType == ChatType.audio) {
        webRtcCubit.add(WebRtcAudioInitEvent(context, webRtcInvitationReq.roomName, userSet, screenWidth, screenHeight));
        return const WebRtcAudioPage();
      } else {
        webRtcCubit.add(WebRtcVideoInitEvent(context, webRtcInvitationReq.roomName, userSet, screenWidth, screenHeight));
        return const WebRtcVideoPage();
      }
    }));
  }

  _reject(BuildContext context) {
    var rpcWebRtcService = RpcWebRtcService();
    rpcWebRtcService
        .sendWebRtcInvitationResult(
            WebRtcInvitationResultReq(toUserId: webRtcInvitationReq.fromUserId!, isAccept: false))
        .then((okResp) => _logger.i('[WebRtcClient reject invitation], success'));
    overlayEntry?.remove();
  }
}
